import {
  Badge,
  ConfigProvider,
  Modal,
  Table,
  Input,
  Form,
  Button,
  message,
} from 'antd';
import dayjs from 'dayjs';
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Status } from '@/enums/withdraw';
import API from '@/http';
import TextArea from 'antd/es/input/TextArea';
import { TableRowSelection } from 'antd/es/table/interface';

interface ColProps {
  children: React.ReactNode;
  head?: boolean;
  filter?: boolean;
}

interface StatusProps {
  status: Status;
}

interface HistoryTableProps {
  datas: any[];
  currentPage: number;
  totalPage: number;
  limit: number;
  onPageClick: (page: number) => void;
}

function Col({ children, head, filter }: ColProps) {
  return (
    <div
      className={`flex p-4 text-14 leading-140 ${head ? 'bg-f3 font-medium' : null} ${filter ? 'cursor-pointer' : null}`}
    >
      {children}
      {filter ? (
        <div className="ml-2 flex flex-col justify-between">
          <div className="h-0 w-0 border-x-[6px] border-b-[7px] border-t-0 border-solid border-[transparent_transparent_#7B7B7B_transparent]"></div>
          <div className="h-0 w-0 border-x-[6px] border-b-0 border-t-[7px] border-solid border-[#7B7B7B_transparent_transparent_transparent]"></div>
        </div>
      ) : null}
    </div>
  );
}

function StatusCol({ status }: StatusProps) {
  const { t } = useTranslation();
  const val =
    status === Status.Cancel
      ? { text: t('cancel'), color: 'bg-[#F00]' }
      : status === Status.Done
        ? { text: t('done'), color: 'bg-[#77D6B4]' }
        : status === Status.ToBeBilled
          ? { text: t('toBeBilled'), color: 'bg-[#FF9000]' }
          : status === Status.Pending
            ? { text: t('pending'), color: 'bg-[#D9D9D9]' }
            : { text: '', color: '' };

  return (
    <div className="flex items-center space-x-2 p-4">
      <div className={`h-2 w-2 rounded-full ${val.color}`}></div>
      <div>{val.text}</div>
    </div>
  );
}

function HistoryTable({
  datas,
  currentPage,
  totalPage,
  limit,
  onPageClick,
}: HistoryTableProps) {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [form] = Form.useForm();
  const [messageApi, contextHolder] = message.useMessage();
  const from = (currentPage - 1) * limit + 1;
  const to = from + limit - 1;
  const { t } = useTranslation();
  const showLeftEtc = currentPage >= 5;
  const showRightEtc = totalPage - currentPage >= 4;
  const columns = [
    {
      title: t('WithdrawalNo'),
      dataIndex: 'apply_remark',
      key: 'apply_remark',
      sorter: true,
    },
    {
      title: t('withdrawalAmount'),
      dataIndex: 'deduct_amount',
      key: 'deduct_amount',
      sorter: (a: any, b: any) => a - b,
    },
    {
      title: t('applicationDate'),
      dataIndex: 'created_at',
      key: 'created_at',
      sorter: (a: any, b: any) => (dayjs(a).isAfter(dayjs(b)) ? 1 : -1),
    },
  ];
  const isMobile = useMemo(() => {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
      navigator.userAgent
    );
  }, []);

  const rowSelection: TableRowSelection<any> = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(
        `selectedRowKeys: ${selectedRowKeys}`,
        'selectedRows: ',
        selectedRows
      );
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
    selections: false,
  };

  const columns_additional = [
    {
      title: t('status'),
      dataIndex: 'status_str',
      key: 'status',
      render: (_: any, e: any) => (
        <div className='flex justify-center'>
          <div className='text-center w-[74px] text-14 rounded-sm' style={{backgroundColor: getBadgeColor(e.status)}}>{e.status_str}</div>
        </div>
      ),
    },
    {
      title: t('operation'),
      dataIndex: 'updated_at',
      key: 'updated_at',
      render: (_: any, e: any) => t('operational'),
    },
  ];

  //TODO: 待确认status枚举类 文档未体现
  const getBadgeColor = (t: any) => {
    switch (t) {
      case 0:
        return '#8C8C8C';
      case 1:
        return '#34c759';
      case 2:
        return '#f42c52';
      case 3:
        return '#ffcc00';
      default:
        return '#ffcc00';
    }
  };

  const sub = (data: any) => {
    API.Withdraw.withdraw({ data })
      .then((res: any) => {
        if (res?.status === 200) {
          setIsModalOpen(false);
          form.resetFields();
          messageApi.open({
            type: 'success',
            content: t('withdrawalSubmitted'),
          });
        }
      })
      .catch((e) => {
        messageApi.open({
          type: 'error',
          content: `${t('withdrawalFailure')} ${e}`,
        });
      });
  };

  return (
    <>
      {contextHolder}
      <div className="px-2">
        <div className="mt-4 flex w-full flex-col rounded-sm bg-black">
          <div className="flex w-full justify-between px-4 py-5 text-14 font-medium leading-140 text-ff">
            <div>{t('historicalWithdrawals')}</div>
            <button
              className="rounded-sm bg-red px-4 py-1 text-white active:translate-y-px"
              onClick={() => setIsModalOpen(true)}
            >
              {t('applyWithdrawal')}
            </button>
          </div>
          <ConfigProvider
            theme={{
              token: {
                colorPrimary: '#77d6d6',
              },
            }}
          >
            <Table
              bordered
              className="history-custom-table px-2"
              columns={isMobile ? columns : [...columns, ...columns_additional]}
              // rowSelection={rowSelection}
              dataSource={datas.map((t) => Object.assign({ key: t?.id }, t))}
              pagination={false}
            />
          </ConfigProvider>
          <div className="flex items-center p-4 text-14 leading-140 text-ff">
            <div className="item-center flex w-full justify-center space-x-7">
              {isMobile ? (
                ' '
              ) : (
                <div className="flex items-center">
                  {from}-{to} / {t('items')}
                </div>
              )}

              <div
                className="flex cursor-pointer items-center"
                onClick={() => onPageClick(Math.max(currentPage - 1, 1))}
              >
                &lt;
              </div>
              {currentPage > 1 ? (
                <div
                  className="flex cursor-pointer items-center justify-center text-7b"
                  onClick={() => onPageClick(1)}
                >
                  1
                </div>
              ) : null}

              {showLeftEtc ? (
                <div className="flex items-center justify-center text-7b">
                  ...
                </div>
              ) : null}

              {currentPage >= 4 ? (
                <div
                  className="flex cursor-pointer items-center justify-center text-7b"
                  onClick={() => onPageClick(currentPage - 2)}
                >
                  {currentPage - 2}
                </div>
              ) : null}

              {currentPage >= 3 ? (
                <div
                  className="flex cursor-pointer items-center justify-center text-7b"
                  onClick={() => onPageClick(currentPage - 1)}
                >
                  {currentPage - 1}
                </div>
              ) : null}

              <div className="flex w-[24px] items-center justify-center rounded-[1px] bg-ff text-center text-black">
                {currentPage}
              </div>

              {currentPage + 1 < totalPage ? (
                <div
                  className="flex cursor-pointer items-center justify-center text-7b"
                  onClick={() => onPageClick(currentPage + 1)}
                >
                  {currentPage + 1}
                </div>
              ) : null}

              {currentPage + 2 < totalPage ? (
                <div
                  className="flex cursor-pointer items-center justify-center text-7b"
                  onClick={() => onPageClick(currentPage + 2)}
                >
                  {currentPage + 2}
                </div>
              ) : null}

              {showRightEtc ? (
                <div className="flex items-center text-7b">...</div>
              ) : null}

              {currentPage < totalPage ? (
                <div
                  className="flex cursor-pointer items-center text-7b"
                  onClick={() => onPageClick(totalPage)}
                >
                  {totalPage}
                </div>
              ) : null}

              <div
                className="flex cursor-pointer items-center"
                onClick={() =>
                  onPageClick(Math.min(currentPage + 1, totalPage))
                }
              >
                &gt;
              </div>
              {isMobile ? (
                ''
              ) : (
                <div className="flex w-[120px] items-center justify-center space-x-1 rounded-sm bg-[#0a0a0f] py-1">
                  <span className="mr-1">
                    {limit}/{t('page')}
                  </span>
                  <span className="h-0 w-0 border-x-4 border-b-0 border-t-[5.5px] border-solid border-[#fff_transparent_transparent_transparent]"></span>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
      <Modal
        open={isModalOpen}
        centered
        closable={false}
        footer={null}
        onOk={() => setIsModalOpen(false)}
        onCancel={() => setIsModalOpen(false)}
        width={isMobile ? '280px' : '379px'}
        className="history-custom-modal"
      >
        <div className="flex flex-col items-center md:w-full">
          <p className="mb-3 text-16 text-ff">{t('applyForWithdrawal')}</p>
          <Form
            form={form}
            className="w-full"
            onFinish={sub}
            layout="vertical"
            requiredMark={false}
          >
            <Form.Item
              name="money"
              label={t('useWithdrawalAmount')}
              rules={[
                { required: true, message: t('psAmount') },
                {
                  validator: (_, value) => {
                    if (value && parseInt(value) > 0) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('請輸入大於0的金額'));
                  },
                },
              ]}
            >
              <Input
                type="number"
                placeholder={t('useWithdrawalAmount')}
                className="rounded-2xl bg-black py-2 text-ff"
              />
            </Form.Item>
            <Form.Item
              label={t('emailAddress')}
              name="email"
              rules={[{ required: true, message: t('psEmail') }]}
            >
              <Input
                type="email"
                placeholder={t('emailAddress')}
                className="rounded-2xl bg-black py-2 text-ff"
              />
            </Form.Item>
            <Form.Item name="remark" label={t('remarks')}>
              <TextArea
                autoSize={{ minRows: 5 }}
                placeholder={t('remarks')}
                className="rounded-2xl bg-black text-ff"
              />
            </Form.Item>
            <Form.Item style={{marginBottom:0}}>
              <div className='flex justify-between w-full flex-wrap items-center'>
                <Button
                onClick={() => setIsModalOpen(false)}
                  className="md:mt-8 h-[30px] md:h-[38px] flex-1  rounded-full border-none bg-7b px-4 md:py-1 text-14 text-white active:translate-y-px"
                >
                  {t('cancel')}
                </Button>
                <div className='w-[14px]'></div>
                <Button
                  htmlType="submit"
                  className="md:mt-8 h-[30px] md:h-[38px] flex-1 rounded-full border-none bg-red px-4 md:py-1 text-14 text-white active:translate-y-px"
                >
                  {t('submit')}
                </Button>
              </div>
            </Form.Item>
          </Form>
        </div>
      </Modal>
    </>
  );
}

export default HistoryTable;
